<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error.sync="error"
    error-text="加载失败，请点击重试"
    :immediate-check="false"
    @load="onLoad"
  >
    <comment-item
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @reply-click="$emit('reply-click', $event)"
    />
  </van-list>
</template>

<script>
import { getComments } from "@/api/comment";
import CommentItem from "../comment-item";
export default {
  name: "CommentList",
  props: {
    source: {
      type: [Number, String, Object],
      required: true,
    },
    list: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      validate(value) {
        return ["a", "c"].includes(value);
      },
      default: "a",
    },
  },
  components: {
    CommentItem,
  },
  data() {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null, // 请求下一页数据的页码
      limit: 10, // (分页，每页显示多少条)
      error: false, // 错误信息，默认false
    };
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 组件方法
  methods: {
    async onLoad() {
      try {
        //1,获取数据
        const { data } = await getComments({
          type: this.type,
          source: this.source.toString(),
          offset: this.offset,
          limit: this.limit,
        });

        // 传递给父组件
        this.$emit("onload-success", data.data);

        //2，将数据添加到表中
        const { results } = data.data;
        this.list.push(...results);

        //3,将loading设置为true
        this.loading = false;

        //4,判断是否还有数据
        if (results.length) {
          // 有就更新下一页的数据页码
          this.offset = data.data.last_id;
        } else {
          // 没有就将finished设置结束
          this.finished = true;
        }
      } catch (err) {
        this.error = true;
        this.loading = false;
      }
    },
  },
  created() {
    this.loading = true;
    this.onLoad();
  },
  mounted() {},
};
</script>

<style scoped lang="less"></style>
